package com.geektime.hello;

import com.geektime.hello.entity.User;
import com.geektime.hello.mapper.UserMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

import java.io.IOException;
import java.io.InputStream;

public class OrmRunDemo {
    public static void main(String[] args) throws IOException {
        hibernate();
        mybatis();
    }

    /**
     * hibernate 配置文件内容和实体类字段要相一一对应（必须）
     */
    private static void hibernate() {
        Configuration configuration = new Configuration();
        //默认hibernate.cfg.xml
        configuration.configure("cfg/hibernate.cfg.xml");
        SessionFactory sessionFactory = configuration.buildSessionFactory();
        Session session = sessionFactory.openSession();

        Transaction transaction = session.getTransaction();
        transaction.begin();

        session.save(new Object());

        transaction.commit();
        session.close();
    }

    /**
     * mybatis  配置文件内容和实体类字段无需一一对应，通过namespace配置的mapper关联
     *          curd-id需要和方法名一一对应（必须）
     * @throws IOException
     */
    private static void mybatis() throws IOException {
        InputStream inputStream = Resources.getResourceAsStream("cfg/mybatis-config.xml");
        SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession session = sessionFactory.openSession();

        UserMapper userMapper = session.getMapper(UserMapper.class);
        userMapper.insert(new User());
    }
}
